package com.ks.user.service.impl;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ks.core.constant.Const;
import com.ks.core.exception.GunsException;
import com.ks.core.util.DateUtil;
import com.ks.core.util.JsonUtil;
import com.ks.core.util.ToolUtil;
import com.ks.user.dao.MicroAppMapper;
import com.ks.user.entity.MicroApp;
import com.ks.user.entity.TemplateFrame;
import com.ks.user.service.IBaseSysConfigService;
import com.ks.user.service.IMicroAppService;
import com.ks.user.service.ITemplateFrameService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 小程序-授权在平台上发布的小程序的基本信息 服务实现类
 * </p>
 *
 * @author kingdee123
 * @since 2020-12-24
 */
@Service
public class MicroAppServiceImpl extends ServiceImpl<MicroAppMapper, MicroApp> implements IMicroAppService {
    @Resource
    private MicroAppMapper microAppMapper;
    @Resource
    private IBaseSysConfigService baseSysConfigService;
    @Resource
    private ITemplateFrameService templateFrameService;


    @Override
    public MicroApp getMicroApp(String authCode, int time, int tenantId) {
        MicroApp app = new MicroApp();
        Map<String, Object> map = new HashMap<>();
        map.put("component_appid", baseSysConfigService.getComponentAppId());
        map.put("authorization_code", authCode);
        String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" + baseSysConfigService.getComponentAccessToken(), JsonUtil.mapToJsonStr(map));
        Map<Object, Object> objectObjectMap = JsonUtil.jsonStrToMap(post);
        if (ToolUtil.isNotEmpty(objectObjectMap.get("authorization_info"))) {
            Map<Object, Object> authorization_info = JsonUtil.jsonStrToMap(objectObjectMap.get("authorization_info").toString());
            app.setAppId(authorization_info.get("authorizer_appid").toString());
            MicroApp microApp = microAppMapper.selectOne(app);
            if (ToolUtil.isNotEmpty(microApp)) {
                if (microApp.getTenantID() == tenantId) {
                    microApp.setAuthCode(authCode);
                    microApp.setAuthorizationInfo(objectObjectMap.get("authorization_info").toString());
                    microApp.setAuthorizerAccessToken(authorization_info.get("authorizer_access_token").toString());
                    microApp.setAuthorizerRefreshToken(authorization_info.get("authorizer_refresh_token").toString());
                    microApp.setTokenTimeout(DateUtil.getAfterMinuteDate(new Date(), 7200 / 60));
                    microApp.setExpiresIn(authorization_info.get("expires_in").toString());
                    microApp.setUpdateTime(new Date());
                    microAppMapper.updateById(microApp);
                    return microApp;
                } else {
                    //说明该租户的小程序重新授权给另一个租户了
                    //删除原来的租户绑定的小程序信息，
                    microAppMapper.deleteById(microApp.getId());
                }
            }
            MicroApp microApp1 = MicroApp(tenantId);
            if (ToolUtil.isNotEmpty(microApp1)) {
                throw new GunsException("当前租户已经授权过小程序了,只能授权一个小程序！");
            }
            app.setAppId(authorization_info.get("authorizer_appid").toString());
            app.setAuthCode(authCode);
            app.setTenantID(tenantId);
            app.setDataType("TENANT");
            app.setAuthorizationInfo(objectObjectMap.get("authorization_info").toString());
            app.setAuthorizerAccessToken(authorization_info.get("authorizer_access_token").toString());
            app.setTokenTimeout(DateUtil.getAfterMinuteDate(new Date(), 7200 / 60));
            app.setExpiresIn(authorization_info.get("expires_in").toString());
            app.setAuthorizerRefreshToken(authorization_info.get("authorizer_refresh_token").toString());
        } else {
            throw new GunsException("小程序授权码回调错误！！！");
        }
        List<TemplateFrame> templateList = templateFrameService.getTemplateList(tenantId);
        if (ToolUtil.isNotEmpty(templateList)) {
            for (TemplateFrame frame : templateList) {
                frame.setSMicroAppID(app.getAppId());
                templateFrameService.updateById(frame);
            }
        }
        microAppMapper.insert(app);
        return app;
    }

    @Override
    public MicroApp getMicroAppInfo(String appId) {
        MicroApp microApp = new MicroApp();
        microApp.setAppId(appId);
        MicroApp app = microAppMapper.selectOne(microApp);
        if (ToolUtil.isNotEmpty(app)) {
            return app;
        } else {
            throw new GunsException("该小程序未授权在本平台！！！！");
        }
    }

    @Override
    public MicroApp MicroApp(int tenantId) {
        MicroApp microApp = new MicroApp();
        microApp.setTenantID(tenantId);
        microApp.setDelMark(Const.DEL_FLAG_NORMAL);
        MicroApp app = microAppMapper.selectOne(microApp);
        return app;
    }

    @Override
    public void updateMicroApp(String appId, String authorizer_refresh_token) {
        Map<String, Object> map = new HashMap<>();
        map.put("component_appid", baseSysConfigService.getComponentAppId());
        map.put("authorizer_appid", appId);
        map.put("authorizer_refresh_token", authorizer_refresh_token);
        String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=" + baseSysConfigService.getComponentAccessToken(), JsonUtil.mapToJsonStr(map));
        Map<Object, Object> objectObjectMap = JsonUtil.jsonStrToMap(post);
        if (ToolUtil.isNotEmpty(objectObjectMap)) {
            System.out.println("当前更新的小程序appid:" + appId);
            System.out.println("更新结果:" + objectObjectMap);
            MicroApp microAppInfo = getMicroAppInfo(appId);
            if (ToolUtil.isNotEmpty(microAppInfo)) {
                microAppInfo.setAuthorizerAccessToken(objectObjectMap.get("authorizer_access_token").toString());
                microAppInfo.setAuthorizerRefreshToken(objectObjectMap.get("authorizer_refresh_token").toString());
                microAppInfo.setUpdateTime(new Date());
                microAppMapper.updateById(microAppInfo);
            }
        }

    }
}
